package com.peng.rpc.socket.util;

import com.peng.rpc.entity.RpcRequest;
import com.peng.rpc.entity.RpcResponse;
import com.peng.rpc.enumeration.PackageType;
import com.peng.rpc.enumeration.RpcError;
import com.peng.rpc.exception.RpcException;
import lombok.extern.slf4j.Slf4j;
import com.peng.rpc.serializer.*;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author Wonderson
 * @email wpp.ds@foxmail.com
 * @date 2022-03-03 20:38
 */
@Slf4j
public class ObjectReader {

    private static final int MAGIC_NUMBER = 0xCAFEBABE;

    public static Object readObject(InputStream is) throws IOException {
        byte[] buf = new byte[4];
        is.read(buf);
        int magicNum = bytesToInt(buf);
        if (magicNum != MAGIC_NUMBER) {
            log.error("不合法的数据包");
            throw new RpcException(RpcError.UNKNOWN_PROTOCOL);
        }

        is.read(buf);
        int packageType = bytesToInt(buf);
        Class<?> packageTypeClass;
        if (packageType ==  PackageType.REQUEST_PACKAGE.getCode()) {
            packageTypeClass = RpcRequest.class;
        } else if (packageType == PackageType.RESPONSE_PACKAGE.getCode()) {
            packageTypeClass = RpcResponse.class;
        } else {
            log.error("不支持的协议包");
            throw new RpcException(RpcError.UNKNOWN_PACKAGE_TYPE);
        }

        is.read(buf);
        int serializerCode = bytesToInt(buf);
        CommonSerializer serializer = CommonSerializer.getSerializerByCode(serializerCode);
        if (serializer == null) {
            log.error("不支持的序列化方式");
            throw new RpcException(RpcError.UNKNOWN_SERIALIZER);
        }

        is.read(buf);
        int length = bytesToInt(buf);
        byte[] bytes = new byte[length];
        is.read(bytes);
        return serializer.deserialize(bytes, packageTypeClass);
    }

    public static int bytesToInt(byte[] src) {
        return ((src[0] & 0xFF)<<24)
                |((src[1] & 0xFF)<<16)
                |((src[2] & 0xFF)<<8)
                |(src[3] & 0xFF);
    }
}
